package com.weme.chat.adapter

import android.content.Context
import android.graphics.Color
import android.text.TextUtils
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.RecyclerView
import com.chad.library.adapter.base.BaseMultiItemAdapter
import com.google.gson.Gson
import com.makeramen.roundedimageview.RoundedImageView
import com.weme.chat.ChatActivity
import com.weme.chat.R
import com.weme.chat.bean.CallMessage
import com.weme.chat.bean.GiftMessage
import com.weme.chat.databinding.*
import com.weme.common.util.*
import com.weme.common.util.TimeUtils.isTimestampDifferenceGreaterThanTwoMinutes
import com.weme.common.view.SmoothConstraintLayout
import com.weme.common.view.SmoothImageView
import io.agora.chat.ChatMessage
import io.agora.chat.CustomMessageBody
import io.agora.chat.ImageMessageBody
import io.agora.chat.TextMessageBody
import org.w3c.dom.Text

class ChatAdapter(var head:String) : BaseMultiItemAdapter<ChatMessage>()  {
    var time = 0L


    var isMeSend = false

    class ItemSendText(viewBinding: ItemChatSendContentBinding) : RecyclerView.ViewHolder(viewBinding.root)
    class ItemReceiveText(viewBinding: ItemChatReceiveContentBinding) : RecyclerView.ViewHolder(viewBinding.root)

    class ItemSendImag(viewBinding: ItemChatSendImageviewBinding) : RecyclerView.ViewHolder(viewBinding.root)
    class ItemReceiveImag(viewBinding: ItemChatReceiveImageviewBinding) : RecyclerView.ViewHolder(viewBinding.root)


    class ItemSendCall(viewBinding: ItemChatSendCallBinding) : RecyclerView.ViewHolder(viewBinding.root)
    class ItemReceiveCall(viewBinding: ItemChatReceiveCallBinding) : RecyclerView.ViewHolder(viewBinding.root)



    class ItemSendGift(viewBinding: ItemChatSendGiftBinding) : RecyclerView.ViewHolder(viewBinding.root)
    class ItemReceiveGift(viewBinding: ItemChatReceiveGiftBinding) : RecyclerView.ViewHolder(viewBinding.root)



    // 在 init 初始化的时候，添加多类型
    init {
        addItemType(ITEM_TYPE_SEND_TEXT, object : OnMultiItemAdapterListener<ChatMessage, ItemSendText> { // 类型 1
            override fun onCreate(context: Context, parent: ViewGroup, viewType: Int): ItemSendText { // 创建 viewholder
                val viewBinding = ItemChatSendContentBinding.inflate(LayoutInflater.from(context), parent, false)
                return ItemSendText(viewBinding)
            }

            override fun onBind(holder: ItemSendText, position: Int, item: ChatMessage?) {
                item?.apply {
                    val tvContent = holder.itemView.findViewById<TextView>(R.id.tvContent)
                    if(item.body is TextMessageBody){
                        (item.body as TextMessageBody)
                        tvContent.text = (item.body as TextMessageBody).message
                        initSendView(holder, item)
                    }else{
                        Log.e("chat",item.body.toString())

                    }


                }
            }
        })
        addItemType(ITEM_TYPE_RECEIVE_TEXT, object : OnMultiItemAdapterListener<ChatMessage, ItemReceiveText> { // 类型 1
            override fun onCreate(context: Context, parent: ViewGroup, viewType: Int): ItemReceiveText { // 创建 viewholder
                val viewBinding = ItemChatReceiveContentBinding.inflate(LayoutInflater.from(context), parent, false)
                return ItemReceiveText(viewBinding)
            }

            override fun onBind(holder: ItemReceiveText, position: Int, item: ChatMessage?) {
                item?.apply {
                    val tvContent = holder.itemView.findViewById<TextView>(R.id.tvContent)
                   val tvTranslate = holder.itemView.findViewById<TextView>(R.id.tvTranslate)
                   val vLine = holder.itemView.findViewById<View>(R.id.vLine)


                    tvContent.text = (item.body as TextMessageBody).message
                    val imTranslate = holder.itemView.findViewById<ImageView>(R.id.imTranslate)
                    try {
                        if((item.body as TextMessageBody).targetLanguages.isNotEmpty()){
                            vLine.visible()
                            tvTranslate.visible()
                            imTranslate.gone()
                            tvTranslate.text = (item.body as TextMessageBody).targetLanguages[0]

                        }else{
                            vLine.gone()
                            tvTranslate.gone()
                        }

                    }catch (e:Exception){
                        vLine.gone()
                        tvTranslate.gone()

                    }

                 //   item.setAttribute()
                    initReceoveView(holder, item)


                }
            }
        }).addItemType(ITEM_TYPE_SEND_IMAGE, object : OnMultiItemAdapterListener<ChatMessage, ItemSendImag> { // 类型 2
            override fun onCreate(context: Context, parent: ViewGroup, viewType: Int): ItemSendImag { // 创建 viewholder
                val viewBinding = ItemChatSendImageviewBinding.inflate(LayoutInflater.from(context), parent, false)
                return ItemSendImag(viewBinding)
            }

            override fun onBind(holder: ItemSendImag, position: Int, item: ChatMessage?) { // 绑定 item 数据
                item?.apply {
                    val simImg = holder.itemView.findViewById<SmoothImageView>(R.id.simImg)
                    simImg.loadChatImage((item.body as ImageMessageBody).remoteUrl)
                 //   Glide.with(simImg).load((item.body as ImageMessageBody).remoteUrl).into(simImg)
                    initSendView(holder, item)
                }

            }

            override fun isFullSpanItem(itemType: Int): Boolean { // 使用GridLayoutManager时，此类型的 item 是否是满跨度
                return true
            }

        }).addItemType(ITEM_TYPE_RECEIVE_IMAGE, object : OnMultiItemAdapterListener<ChatMessage, ItemReceiveImag> { // 类型 2
            override fun onCreate(context: Context, parent: ViewGroup, viewType: Int): ItemReceiveImag { // 创建 viewholder
                val viewBinding = ItemChatReceiveImageviewBinding.inflate(LayoutInflater.from(context), parent, false)
                return ItemReceiveImag(viewBinding)
            }

            override fun onBind(holder: ItemReceiveImag, position: Int, item: ChatMessage?) { // 绑定 item 数据
                item?.apply {
                    val simImg = holder.itemView.findViewById<SmoothImageView>(R.id.simImg)
                    simImg.loadChatImage((item.body as ImageMessageBody).remoteUrl)
                    initReceoveView(holder, item)

                }
            }

            override fun isFullSpanItem(itemType: Int): Boolean { // 使用GridLayoutManager时，此类型的 item 是否是满跨度
                return true
            }

        }).addItemType(ITEM_TYPE_SEND_CALL, object : OnMultiItemAdapterListener<ChatMessage, ItemSendCall> { // 类型 2
            override fun onCreate(context: Context, parent: ViewGroup, viewType: Int): ItemSendCall { // 创建 viewholder
                val viewBinding = ItemChatSendCallBinding.inflate(LayoutInflater.from(context), parent, false)
                return ItemSendCall(viewBinding)
            }

            override fun onBind(holder: ItemSendCall, position: Int, item: ChatMessage?) { // 绑定 item 数据
                item?.let {
                    initSendView(holder, item)


                    val params = (item.body as CustomMessageBody).params
                    val jsonString = Gson().toJson(params)
                    val callMessage = Gson().fromJson(jsonString, CallMessage::class.java)

                    val scvItem = holder.itemView.findViewById<SmoothConstraintLayout>(R.id.scvItem)
                    val imCallBtn = holder.itemView.findViewById<ImageView>(R.id.imCallBtn)
                    val tvTitle = holder.itemView.findViewById<TextView>(R.id.tvTitle)
                    val tvBen = holder.itemView.findViewById<TextView>(R.id.tvBtn)
                    tvBen.text = if (callMessage.callTime == 0L) context.getText(com.example.resources.R.string.chat_call_pick) else context.getText(com.example.resources.R.string.chat_call_back)

                    val tvCallTime = holder.itemView.findViewById<TextView>(R.id.tvCallTime)
                    tvCallTime.setVisible(callMessage.callTime != 0L)

                    val hours = callMessage.callTime / 3600
                    val minutes = (callMessage.callTime % 3600) / 60
                    val remainingSeconds = callMessage.callTime % 60
                    val formattedTime = String.format("%02d:%02d:%02d", hours, minutes, remainingSeconds)

                    tvCallTime.text = formattedTime
                    scvItem.setColor(Color.parseColor("#33FF375F"))
                    if (callMessage.isMatching) { //如果是匹配电话

                        scvItem.setColor(ContextCompat.getColor(context, com.example.resources.R.color.app_btn_colors_20),0)
                        imCallBtn.setImageResource(com.example.resources.R.mipmap.icon_private_live)
                        tvTitle.text = context.getText(com.example.resources.R.string.chat_match_back)
                    } else {
                        if(callMessage.callTime == 0L){
                            scvItem.setColor(ContextCompat.getColor(context, com.example.resources.R.color.app_btn_colors_20))
                        }else{
                            scvItem.setColor(ContextCompat.getColor(context, com.example.resources.R.color.app_btn_start), ContextCompat.getColor(context, com.example.resources.R.color.app_btn_end))
                        }
                        imCallBtn.setImageResource(if (callMessage.callTime == 0L) com.example.resources.R.mipmap.icon_private_error else com.example.resources.R.mipmap.icon_private_on)
                        tvTitle.text = context.getText(if (callMessage.callTime == 0L) com.example.resources.R.string.call_history_outgoing_error else com.example.resources.R.string.chat_call_private)
                        scvItem.setColor(Color.parseColor("#339146FF"))
                    }



                }
            }

            override fun isFullSpanItem(itemType: Int): Boolean { // 使用GridLayoutManager时，此类型的 item 是否是满跨度
                return true
            }

        }).addItemType(ITEM_TYPE_RECEIVE_CALL, object : OnMultiItemAdapterListener<ChatMessage, ItemReceiveCall> { // 类型 2
            override fun onCreate(context: Context, parent: ViewGroup, viewType: Int): ItemReceiveCall { // 创建 viewholder
                val viewBinding = ItemChatReceiveCallBinding.inflate(LayoutInflater.from(context), parent, false)
                return ItemReceiveCall(viewBinding)
            }

            override fun onBind(holder: ItemReceiveCall, position: Int, item: ChatMessage?) { // 绑定 item 数据
                item?.let {
                    initReceoveView(holder, item)

                    val params = (item.body as CustomMessageBody).params
                    val jsonString = Gson().toJson(params)
                    val callMessage = Gson().fromJson(jsonString, CallMessage::class.java)

                    val scvItem = holder.itemView.findViewById<SmoothConstraintLayout>(R.id.scvItem)
                    val imCallBtn = holder.itemView.findViewById<ImageView>(R.id.imCallBtn)
                    val tvTitle = holder.itemView.findViewById<TextView>(R.id.tvTitle)
                    val tvBen = holder.itemView.findViewById<TextView>(R.id.tvBtn)
                    val tvCallTime = holder.itemView.findViewById<TextView>(R.id.tvCallTime)
                    tvCallTime.setVisible(callMessage.callTime != 0L)

                    val hours = callMessage.callTime / 3600
                    val minutes = (callMessage.callTime % 3600) / 60
                    val remainingSeconds = callMessage.callTime % 60
                    val formattedTime = String.format("%02d:%02d:%02d", hours, minutes, remainingSeconds)

                    tvCallTime.text = formattedTime
                    tvBen.text = if (callMessage.callTime == 0L) context.getText(com.example.resources.R.string.chat_call_pick) else context.getText(com.example.resources.R.string.chat_call_back)
                    scvItem.setColor(Color.parseColor("#33FF375F"))
                    if (callMessage.isMatching) { //如果是匹配电话
                        scvItem.setColor(ContextCompat.getColor(context, com.example.resources.R.color.app_btn_colors_20))
                        imCallBtn.setImageResource(com.example.resources.R.mipmap.icon_private_live)
                        tvTitle.text = context.getText(com.example.resources.R.string.chat_match_back)
                    } else {
                        if(callMessage.callTime == 0L){
                            scvItem.setColor(ContextCompat.getColor(context, com.example.resources.R.color.app_btn_colors_20))
                        }else{
                            scvItem.setColor(ContextCompat.getColor(context, com.example.resources.R.color.app_btn_start), ContextCompat.getColor(context, com.example.resources.R.color.app_btn_end))
                        }
                         imCallBtn.setImageResource(if (callMessage.callTime == 0L) com.example.resources.R.mipmap.icon_private_error else com.example.resources.R.mipmap.icon_private_in)
                        tvTitle.text = context.getText(if (callMessage.callTime == 0L) com.example.resources.R.string.chat_call_missed else com.example.resources.R.string.chat_call_private)
                        if (callMessage.callTime == 0L){
                            scvItem.setColor(Color.parseColor("#339146FF"))
                        }

                    }
                }
            }
        }).addItemType(ITEM_TYPE_SEND_GIFT, object : OnMultiItemAdapterListener<ChatMessage, ItemSendGift> { // 类型 2
            override fun onCreate(context: Context, parent: ViewGroup, viewType: Int): ItemSendGift { // 创建 viewholder
                val viewBinding = ItemChatSendGiftBinding.inflate(LayoutInflater.from(context), parent, false)
                return ItemSendGift(viewBinding)
            }

            override fun onBind(holder: ItemSendGift, position: Int, item: ChatMessage?) { // 绑定 item 数据
                item?.apply {
                    initSendView(holder, item)
                    val params = (item.body as CustomMessageBody).params
                    val jsonString = Gson().toJson(params)
                    val giftMessage = Gson().fromJson(jsonString, GiftMessage::class.java)
                    val imGift = holder.itemView.findViewById<ImageView>(R.id.imGift)
                    holder.itemView.findViewById<TextView>(R.id.tvGiftName).text = giftMessage.giftName
                    imGift.loadImage(giftMessage.giftIcon)
                }

            }

            override fun isFullSpanItem(itemType: Int): Boolean { // 使用GridLayoutManager时，此类型的 item 是否是满跨度
                return true
            }

        }).addItemType(ITEM_TYPE_RECEIVE_GIFT, object : OnMultiItemAdapterListener<ChatMessage, ItemReceiveGift> { // 类型 2
            //TODO  用户没有接收礼物
            override fun onCreate(context: Context, parent: ViewGroup, viewType: Int): ItemReceiveGift { // 创建 viewholder
                val viewBinding = ItemChatReceiveGiftBinding.inflate(LayoutInflater.from(context), parent, false)
                return ItemReceiveGift(viewBinding)
            }

            override fun onBind(holder: ItemReceiveGift, position: Int, item: ChatMessage?) { // 绑定 item 数据
                item?.apply {
                    initReceoveView(holder, item)
                    val params = (item.body as CustomMessageBody).params
                    val jsonString = Gson().toJson(params)
                    val giftMessage = Gson().fromJson(jsonString, GiftMessage::class.java)
                    val imGift = holder.itemView.findViewById<ImageView>(R.id.imGift)
                    imGift.loadImage(giftMessage.giftImageURL)
                }


            }

            override fun isFullSpanItem(itemType: Int): Boolean { // 使用GridLayoutManager时，此类型的 item 是否是满跨度
                return true
            }

        }).onItemViewType { position, list -> // 根据数据，返回对应的 ItemViewType
            val message = list[position]

            when (message.type) {
                ChatMessage.Type.TXT -> {
                    if (message.direct() == ChatMessage.Direct.SEND) {
                        ITEM_TYPE_SEND_TEXT
                    } else {
                        ITEM_TYPE_RECEIVE_TEXT
                    }
                }
                ChatMessage.Type.IMAGE -> {
                    if (message.direct() == ChatMessage.Direct.SEND) {
                        ITEM_TYPE_SEND_IMAGE
                    } else {
                        ITEM_TYPE_RECEIVE_IMAGE
                    }
                }
                ChatMessage.Type.CUSTOM -> {
                    if ((message.body as CustomMessageBody).event() == AgoraClient.EVENT_TYPING_CALL) {
                        if (message.direct() == ChatMessage.Direct.SEND) {
                            ITEM_TYPE_SEND_CALL
                        } else {
                            ITEM_TYPE_RECEIVE_CALL
                        }
                    } else if ((message.body as CustomMessageBody).event() == AgoraClient.EVENT_TYPING_GIFT) {
                        if (message.direct() == ChatMessage.Direct.SEND) {
                            ITEM_TYPE_SEND_GIFT
                        } else {
                            ITEM_TYPE_RECEIVE_GIFT
                        }
                    } else {
                        -1
                    }

                }
                ChatMessage.Type.VIDEO -> {
                    if (message.direct() == ChatMessage.Direct.SEND) {
                        ITEM_TYPE_SEND_VIDEO
                    } else {
                        ITEM_TYPE_RECEIVE_VIDEO
                    }
                }
                else -> -1
            }


        }
    }

    fun initSendView(holder: RecyclerView.ViewHolder, item: ChatMessage) {

        showTime(item.msgTime, holder.itemView.findViewById(R.id.tvTime),holder.absoluteAdapterPosition)
        holder.itemView.findViewById<ImageView>(R.id.imSendError).setVisible(item.isDelivered)
        isMeSend = true
    }

    fun initReceoveView(holder: RecyclerView.ViewHolder, item: ChatMessage) {

        val rimHead = holder.itemView.findViewById<RoundedImageView>(R.id.rimHead)
       val tvTime = holder.itemView.findViewById<TextView>(R.id.tvTime)
        Log.e("tag",head)
        if(holder.absoluteAdapterPosition == 0){
            time = item.msgTime
            tvTime.visible()
            tvTime.text = TimeUtils.formatTimestamp(time)
            rimHead?.visible()
            rimHead?.loadImage(head)
        }else{
            showTime(item.msgTime, tvTime,holder.absoluteAdapterPosition)
            if(isMeSend||tvTime.visibility == View.VISIBLE){
                rimHead?.visible()
                rimHead?.loadImage(head)
            }else if(items.size>holder.absoluteAdapterPosition-1){
                if(items.get(holder.absoluteAdapterPosition-1).direct() == ChatMessage.Direct.SEND){
                    rimHead?.visible()
                    rimHead?.loadImage(head)
                }
            }else{
                rimHead?.invisible()
            }
        }


        isMeSend = false


    }

    private fun showTime(msgTime: Long, tvTime: TextView,position:Int) :Boolean{
        tvTime.gone()
        if (time.isTimestampDifferenceGreaterThanTwoMinutes(msgTime) || position == 0) {
            time = msgTime
            tvTime.visible()
            tvTime.text = TimeUtils.formatTimestamp(time)
            return true
        }
        return false
    }

    companion object {
        const val ITEM_TYPE_SEND_TEXT = 0
        const val ITEM_TYPE_RECEIVE_TEXT = 1
        const val ITEM_TYPE_SEND_IMAGE = 2
        const val ITEM_TYPE_RECEIVE_IMAGE = 3
        const val ITEM_TYPE_SEND_CALL = 4
        const val ITEM_TYPE_RECEIVE_CALL = 5
        const val ITEM_TYPE_SEND_VIDEO = 6
        const val ITEM_TYPE_RECEIVE_VIDEO = 7
        const val ITEM_TYPE_SEND_GIFT = 8
        const val ITEM_TYPE_RECEIVE_GIFT = 9
    }



}